﻿using Codinlab.CustomClass.Models;
using Codinlab.CustomClass.Permissions;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Core.Contents;
using Orchard.Localization;
using Orchard.Security;

namespace Codinlab.CustomClass.Drivers {
    public class CustomClassPartDriver : ContentPartDriver<CustomClassPart> {
        private readonly IAuthorizer _authorizer;

        private const string TemplateName = "Parts/CustomClass";

        public CustomClassPartDriver(IAuthorizer authorizer) {
            _authorizer = authorizer;

            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        protected override string Prefix { get { return "CustomClass"; } }

        protected override DriverResult Display(CustomClassPart part, string displayType, dynamic shapeHelper) {
            return new DriverResult();
        }

        protected override DriverResult Editor(CustomClassPart part, dynamic shapeHelper) {
            if (!_authorizer.Authorize(DynamicPermissions.CreateDynamicPermission(CustomClassPermissions.EditCustomClassPart, part.ContentItem.TypeDefinition))) {
                return null;
            }

            return ContentShape("Parts_CustomClass_Edit",
                () => shapeHelper.EditorTemplate(
                    TemplateName: TemplateName,
                    Model: part,
                    Prefix: Prefix)
                );
        }

        protected override DriverResult Editor(CustomClassPart part, IUpdateModel updater, dynamic shapeHelper) {
            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }
    }
}